﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Platform : MonoBehaviour
{
    public Rigidbody2D platform_Rigi;
    private float dropSelfTime;


    //为什么不用Awake、Start很明显，它需 ”每次“ 激活都重新初始化自己（这不就是改变克隆出来单个物体属性的方法吗？？？）
    private void OnEnable()
    {
        InitSelf();
    }


    /// <summary>
    /// 每个平台克隆出来后要初始化自己，尤其是Rigidbody2D这种是自己的属性，不是预制体的
    /// 自身的数据也要初始化，一般是不会沿用上次放回对象池时的值的
    /// </summary>
    private void InitSelf()
    {
        platform_Rigi = GetComponent<Rigidbody2D>();
        platform_Rigi.bodyType = RigidbodyType2D.Static;
        dropSelfTime = 0;
    }

    private void Update()
    {
        if (GameManager.Instance.isGameStart && DataManager.Instance.mGameData.isStartDrop)
        {
            if (!GameManager.Instance.isPause)
            {
                DropSelfTimer();                
            }
        }
        if (GameManager.Instance.isGameOver)
        {
            StartCoroutine(BackSelf());
        }
    }

    /// <summary>
    /// 自身掉落计时器
    /// </summary>
    private void DropSelfTimer()
    {
        dropSelfTime += Time.deltaTime;
        if (dropSelfTime >= DataManager.Instance.mGameData.DropTime)
        {
            if (platform_Rigi.bodyType != RigidbodyType2D.Dynamic)
            {
                platform_Rigi.bodyType = RigidbodyType2D.Dynamic;
            }            
        } 
    }

    IEnumerator BackSelf()
    {
        yield return new WaitForSeconds(2);
        ObjectPool.Instance.BackObj(gameObject);
    }

    /// <summary>
    /// 给BottomWall加上刚体组件是因为“bodyType”只有是Dynamic动态时才可以触发碰撞器
    /// </summary>
    /// <param name="collision"></param>
    public void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "BottomWall")
        {
            ObjectPool.Instance.BackObj(gameObject);
        }
    }
    

    

    
}
